#!/usr/bin/env python
# coding=utf-8


import os
import sys
import re
import codecs
import logging
import pyExcelerator as pE


xlsFileName = r'D:\ylb_work\data\Voice_ID_list_V15.xls'
headerFileName = r'D:\ylb_work\data\waveID_Oversea.h'
logFileName = r'makeconst_Oversea.log'


def init_log():
    logger = logging.getLogger()
    hdlr = logging.FileHandler(logFileName)
    formatter = logging.Formatter('%(asctime)s %(levelname)s:: %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    logger.info('\n\n\n\n\n')
    return logger
logf = init_log()

def sheet_size(sheet):
    keys = sheet[1].keys()
    rows = tuple(u[0] for u in keys)
    cols = tuple(u[1] for u in keys)
    return max(rows), max(cols)


def get_all_constants(xlsfn):
    xls = pE.parse_xls(xlsfn)
    constants = {}
    # only in some sheets
    for sheet in xls[1:8]:
        maxRow, maxCol = sheet_size(sheet)
        sc = sheet[1]
        countSheetConst = 0
        # from row 9
        for row in range(0, maxRow+1):
            # number from row 1
            for col in range(3, maxCol+1, 2):
                if sc.has_key((row, col)):
                    v = unicode(str(sc[(row,col)]))
                    rem = ''
                    if re.match(r'\s*[\dA-Fa-f]+\s*$', v):
                        # comment place from column 2
                        for remCol in range(2, maxCol+1, 2):
                            if sc.has_key((row, remCol)):
                                rem = sc[(row,remCol)]
                                break
                        if rem == '':
                            # warning
                            logf.warning( "Value %s has no comment, sheet: %s, row: %d, column: %d",
                                        v, sheet[0], row, col)
                        if not constants.has_key(v[-6:]):
                            constants[v[-6:]] = rem
                            countSheetConst = countSheetConst + 1
                        else:
                            # warning
                            logf.debug("Value %s has already exists, sheet: %s, row: %d, column: %d",
                                       v, sheet[0], row, col)
        logf.info('Sheet(%s)  has %d constants', sheet[0], countSheetConst)
    return constants


# for test 
def compare():
    all = get_all_constants(xlsFileName)
    part = get_regular_constants(xlsFileName)
    print len(all)
    print len(part)
    print len(all.keys())
    print len(part.keys())
    k1 =  all.keys()
    k2 = part.keys()
    k1.sort()
    k2.sort()
    print k1
    print k2
    for k in all.keys():
        if not part.has_key(k):
            print "different key: %s " % (k,)   


def convert_const_to_varname(v):
    if len(v) != 6:
        raise ValueError()
    typeId = v[0:2]
    if typeId=='10':
        return 'VL_PL_DIRGUIDE_' + v[-4:]
    elif typeId == '20':
        return 'VL_PL_REPLYMSG_' + v[-4:]
    elif typeId == '30':
        return 'VL_PL_CATEGORY_' + v[-4:]
    raise ValueError()

def make_define_line(v, rem):
    vn = convert_const_to_varname(v)
    return 'const DWORD %s =\t%s;\t\t// %s \n' % (vn, '0x'+v, rem)

def write_const_to_header(constants, outfn):
    outf = codecs.open(outfn, 'w', 'utf-8')
    ks = constants.keys()
    ks.sort()
    for k in ks:
        outf.write(make_define_line(k, constants[k]))
    outf.close()



def main():
    cts = get_all_constants(xlsFileName)
    write_const_to_header(cts, headerFileName)


if __name__ == '__main__':
    main()


